package van.planifolia.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO 模拟各个业务的Controller
 * @Author: Van.Planifolia
 * @CreateTime: 2023-01-03  16:22
 * @Version: 1.0
 */
@RestController
public class MessageController {

    @PreAuthorize("hasAuthority('user:query')")
    @RequestMapping("/query")
    public String query(){
        return "查询操作";
    }

    @PreAuthorize("hasAuthority('user:update')")
    @RequestMapping("/update")
    public String update(){
        return "更新操作";
    }

    @PreAuthorize("hasAuthority('user:delete')")
    @RequestMapping("/delete")
    public String delete(){
        return "删除操作";
    }

    @PreAuthorize("hasAuthority('user:insert')")
    @RequestMapping("/insert")
    public String insert(){
        return "插入操作";
    }

    @PreAuthorize("hasAuthority('user:export')")
    @RequestMapping("/export")
    public String export(){
        return "导出操作";
    }

    @RequestMapping("/info")
    public Object info(Principal principal){
        SecurityContext context = SecurityContextHolder.getContext();
        return context.getAuthentication();
    }

    /**
     * 接受错误数据的controller
     * @param request 请求
     * @param response 响应
     * @return 显示给用户的信息
     */
    @RequestMapping("/errorMsg")
    public Object errorMsg(HttpServletRequest request, HttpServletResponse response){
        // 获取异常信息，springSecurity中的异常信息都存放在SPRING_SECURITY_LAST_EXCEPTION中
        AuthenticationException exception = (AuthenticationException) request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        String message = exception.getMessage();
        Map<String,String> errorInfo = new HashMap<>();
        errorInfo.put("code","5001");
        errorInfo.put("message",message);
        return errorInfo;
    }
}
